package com.cr.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.cr.model.Cloth;
import com.cr.model.Customer;
import com.cr.model.MyOrder;
import com.cr.model.OrderDetail;
import com.cr.service.ClothService;
import com.cr.service.CustomerService;
import com.cr.service.MyOrderService;
import com.cr.service.OrderDetailService;

@SuppressWarnings("serial")
public class HandlerServlet extends HttpServlet {

	/**
	 * Constructor of the object.
	 */
	public HandlerServlet() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doPost(request,response);
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		
		
		String action=request.getParameter("action");
		
		if(action.equals("login"))
		{
			
			String username=request.getParameter("username");
			String password=request.getParameter("password");
			
			CustomerService service=new CustomerService();
			
			Customer customer=service.getCustomer(username, password);
			
			if(customer!=null)
			{
				request.getSession().setAttribute("customer", customer);
				request.getRequestDispatcher("index.jsp").forward(request, response);
			}
			else
			{
				request.getRequestDispatcher("login.jsp").forward(request, response);
			}
		}
		else if(action.equals("logout"))
		{
			
			request.getSession().setAttribute("customer", null);
			request.getRequestDispatcher("login.jsp").forward(request, response);
		}
		else if(action.equals("register"))
		{
			
			String username=request.getParameter("username");
			String password=request.getParameter("password");
			Customer customer=new Customer();
			customer.setName(username);
			customer.setPassword(password);
			
			CustomerService service=new CustomerService();
			if(service.addCustomer(customer))
			{
				customer=service.getCustomer(username, password);
				request.getSession().setAttribute("customer", customer);
				request.getRequestDispatcher("index.jsp").forward(request, response);
			}
			else
			{
				request.getRequestDispatcher("register.jsp").forward(request, response);
			}
		}
		else if(action.equals("commit"))
		{
			boolean success=true;
			
			Customer customer=null;
			if(request.getSession().getAttribute("customer")!=null)
			{
				customer=(Customer)request.getSession().getAttribute("customer");
			}
			
			if(customer!=null)
			{
				String clientname=request.getParameter("clientname");
				String province=request.getParameter("province");
				String address=request.getParameter("address");
				String phone=request.getParameter("phone");
				String email=request.getParameter("email");
				String postcode=request.getParameter("postcode");
				String payway=request.getParameter("payway");
				String sendway=request.getParameter("sendway");
				String day=request.getParameter("day");
				
				float total=0;
				
				ClothService clothService=new ClothService();
				MyOrderService orderService=new MyOrderService();
				OrderDetailService detailService=new OrderDetailService();
				
				MyOrder order=new MyOrder();
				order.setCustomerId(customer.getId());
				order.setPayMethod(payway);
				if(postcode!=null)
				{
					order.setPostCode(postcode);
				}
				order.setPostMethod(sendway);
				order.setRecvAddr(address);
				order.setRecvEmail(email);
				order.setRecvName(clientname);
				order.setRecvPhone(phone);
				order.setRecvProvince(province);
				order.setRentDays(Integer.parseInt(day));
				
				
				SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmssS");
				Date now=new Date();
				String code=sdf.format(now);
				order.setCode(code);
				
				if(orderService.addMyOrder(order))
				{
					MyOrder newOrder=orderService.getMyOrder(code);
					
					String clothes=request.getParameter("clothes");
					String[] strs=clothes.split(";");
					for(String str:strs)
					{
						if(str!=null && !str.equals(""))
						{
							String[] temp=str.split(":");
							String id=temp[0];
							String num=temp[1];
							OrderDetail detail=new OrderDetail();
							Cloth cloth=clothService.getCloth(Long.parseLong(id));

							detail.setClothId(cloth.getId());
							detail.setOrderId(newOrder.getId());
							detail.setQuantity(Integer.parseInt(num));
							
							if(detailService.addOrderDetail(detail))
							{
								total+=cloth.getPrice()*Integer.parseInt(num)*Integer.parseInt(day);
							}
							else
							{
								success=false;
							}
						}
					}
					
					newOrder.setTotal(total);
					
					if(!orderService.updateMyOrder(newOrder))
					{
						success=false;
					}
				}
				else
				{
					success=false;
				}
			}
			else
			{
				success=false;
			}
			if(success)
			{
				print(response,"success");
			}
		}
	}

	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}
	
	private void print(HttpServletResponse response,String msg)
	{
		try {
			PrintWriter out = response.getWriter();
			
			out.print(msg);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
